/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-04-15 23:03:32
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-04-16 16:09:59
 * @FilePath: /lesson29/1.sharemem/processa.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include"comm.hpp"
#include"log.hpp"

int main()
{
    Init init;
    //创建共享内存
    int shmid=Createshm();
    // log(Debug,"create share memory done");

    // sleep(5);
    //挂接
    char*shmaddr=(char*)shmat(shmid,nullptr,0);
    // log(Debug,"attach share memory done,shmaddr:0x%x",shmaddr);

    int fd=open(FIFO_FILE,O_RDONLY);
    if(fd<0)
    {
        log(Fatal,"error string: %s , error code: %d\n",strerror(errno),errno);
        exit(FIFO_OPEN_ERR);
    }

    //ipc code
    //一旦有人把数据写到共享内存中，其实我们立马就可以看到了！！！
    //不需要经过系统调用，直接就能看到数据了！
    struct shmid_ds shmds;
    while(1)
    {
        char c;
        ssize_t s=read(fd,&c,1);
        if(s==0)break;
        else if(s<0)break;


        cout<<"client say: "<<shmaddr<<endl;//直接访问共享内存
        sleep(1);

        shmctl(shmid,IPC_STAT,&shmds);

        cout<<"shm size: "<<shmds.shm_segsz<<endl;
        cout<<"shm nattch: "<<shmds.shm_nattch<<endl;
        printf("shm key: 0x%x\n",shmds.shm_perm.__key);
        cout<<"shm mode: "<<shmds.shm_perm.mode<<endl;
        cout<<"--------------------------------"<<endl;
    }

    // sleep(5);

    //去关联
    shmdt(shmaddr);
    // log(Debug,"detach share memory done,shmaddr:0x%x",shmaddr);

    //释放共享内存
    shmctl(shmid,IPC_RMID,nullptr);
    // log(Debug,"destory share memory done,shmid: %d",shmid);
    close(fd);
    
    // log(Debug,"processa quit..");
    return 0;
}